import type { ISuffix, IUpdateSuccessData, IUploadQiNiuParams, IUpToken } from "@/types/upload";
import { getUploadToken } from "@/utils/api/mallGoods";
import { IMG_URL, UPLOAD_URL } from "@/utils/config";
import { uploadImg } from "@/utils/request";
import wangEditor from "wangeditor";

/* 富文本编辑器 */
function userEditor(id: string = "#editor", callback: (newHtml: string) => void) {
  const editor = ref();

  /* 初始化富文本编辑器 */
  function handleInitEditor() {
    const editor = new wangEditor(id);
    editor.config.height = 600;
    //关闭网络路径图片方式
    // editor.customConfig.showLinkImg = false;
    // 配置 server 接口地址
    editor.config.uploadImgServer = UPLOAD_URL;
    editor.config.uploadFileName = "file";

    editor.config.customUploadImg = (resultFiles: Array<File>, insertImgFn: (src: string) => void) => {
      // resultFiles 是 input 中选中的文件列表
      // insertImgFn 是获取图片 url 后，插入到编辑器的方法
      // 上传图片，返回结果，将图片插入到编辑器中
      if (resultFiles.length > 6) {
        ElMessage.warning("每次只能上传五张图片");
        return;
      }
      // const suffix = file.type.split('/')[1];
      /* 循环获取文件后缀信息 */
      const suffixs = [];
      for (let i = 0; i < resultFiles.length; i++) {
        const file = resultFiles[i];
        suffixs.push(file.type.split("/")[1]);
      }
      getUploadToken<IUpToken, ISuffix>({ suffix: suffixs.join(",") }).then(res => {
        for (let i = 0; i < resultFiles.length; i++) {
          const file = resultFiles[i];
          const formdata: IUploadQiNiuParams = {
            file: file,
            token: res.result.upToken,
            key: res.result.fileName[i]
          };
          uploadImg<IUpdateSuccessData>(formdata)
            .then(res => {
              insertImgFn(IMG_URL + "/" + res.key);
            })
            .catch(() => {
              ElMessage.error("服务器繁忙，请稍后再试");
            });
        }
      });
    };
    // 配置 onchange 回调函数，将数据同步到 vue 中
    editor.config.onchange = (newHtml: string) => {
      newHtml = newHtml.replace(/(<img[^>]*style=")([^"]*)/g, "$1$2vertical-align:top;display: block;").replace(/(vertical-align:top;display: block;)\1+/g, "vertical-align:top;display: block;");
      callback(newHtml);
    };
    // 创建编辑器
    editor.create();
    return editor;
  }

  /* 销毁富文本编辑器 */
  function handleDestroyEditor() {
    editor.value?.destroy();
  }
  /* 组件注销后，销毁富文本编辑器  */
  onUnmounted(() => {
    handleDestroyEditor();
  });
  return {
    handleInitEditor,
    handleDestroyEditor
  };
}

export { userEditor };
